package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import io.seata.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {


    @Autowired
    ApUserMapper apUserMapper;
    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        if(dto.getEquipmentId()==null&&dto.getPassword()==null&&dto.getPhone()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 查询登录用户
        if(StringUtils.isNotBlank(dto.getPassword())&&StringUtils.isNotBlank(dto.getPhone())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getStatus, 0).eq(ApUser::getPhone, dto.getPhone()));
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"手机号或者密码错误");
            }
            //获取数据库密码比对
            String dbpassword = apUser.getPassword();
            String dtoPassword = dto.getPassword();
            String md5Password = DigestUtils.md5DigestAsHex((dtoPassword + apUser.getSalt()).getBytes());
            if(!dbpassword.equals(md5Password)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"手机号或者密码错误");
            }
            Map<String,Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("user",apUser);
            apUser.setPassword("");
            apUser.setPhone("");
            apUser.setSalt("");
            return ResponseResult.okResult(apUser);
        }else{
            Map<String,Object> map = new HashMap<>();
//            map.put("token",AppJwtUtil.getToken(dto.getEquipmentId().longValue()));
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
